﻿using AngleSharp.Dom;
using Cxuu.Common;
using Cxuu.Models;
using PetaPoco;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Repository
{
    [AppService]
    public class LogRepository : BaseRepository<LogSql, PetaPocoContext>
    {

        public LogRepository(PetaPocoContext petaPocoContext) : base(petaPocoContext) { }


        public async Task<Page<ViewLogSql>> GetSqlListAsync(int page, int limit, int uid, string orderBy)
        {
            Sql sql = Sql.Builder;
            sql.Select("B.Nickname,A.*,dept.DeptName")
                .From("cxuu_log_sql as A")
                .LeftJoin("cxuu_admin_user as B").On("A.UserId = B.Id");
            sql.LeftJoin("cxuu_admin_dept as dept").On("dept.Id=B.DeptId");

            if (uid != 0)
                sql.Where("A.UserId = @0", uid);

            if (!string.IsNullOrEmpty(orderBy))
                sql.OrderBy(orderBy);

            return await CreateDAO().PageAsync<ViewLogSql>(page, limit, sql);
        }

        public async Task<List<ViewLogSql>> GetListAsync(int uid)
        {
            Sql sql = Sql.Builder;
            sql.Select("*")
                .From("cxuu_log_sql");
            sql.Where("UserId = @0", uid);
            sql.OrderBy("Id desc limit 3");

            return await CreateDAO().FetchAsync<ViewLogSql>(sql);
        }
        public async Task AutoDelAsync(int num)
        {
            int conNum = await CreateDAO().ExecuteScalarAsync<int>("select COUNT(Id) from cxuu_log_sql");
            if (conNum > num)
                await CreateDAO().ExecuteAsync("delete from cxuu_log_sql order by id asc limit 1");
        }

        /// <summary>
        /// 把实体entity添加到数据库
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public  void InsertLog(LogSql logSql)
        {
             CreateDAO().Insert(logSql);
        }
        public async Task<int> Clear()
        {
            return await CreateDAO().ExecuteAsync("TRUNCATE cxuu_log_sql");
        }
    }
}
